package com.zeng.stpro.modules.security.service;

import com.zeng.stpro.modules.app.bean.SysUser;
import com.zeng.stpro.modules.app.mapper.SysMenuMapper;
import com.zeng.stpro.modules.app.mapper.SysUserMapper;
import com.zeng.stpro.modules.security.entity.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZENGZHIJUN
 * @Date 2021/2/4 15:01
 */
@Service("userDetailsService")
public class CustomizeUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)) throw new UsernameNotFoundException("用户或密码错误");

        SysUser dbUser = sysUserMapper.findByUsername(username);
        if (dbUser == null) throw new UsernameNotFoundException("用户或密码错误");

        SysUser user = new SysUser();
        BeanUtils.copyProperties(dbUser, user);

        // 查询 permission 列表
        List<String> permissionValueLise = sysMenuMapper.findPermissionValueListByUsername(username);
        List<String> permissionValueLise2= new ArrayList<>();
        permissionValueLise.forEach(i -> {
            if (!StringUtils.isEmpty(i)) {
                permissionValueLise2.add(i);
            }
        });

        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUserInfo(user);
        securityUser.setPermissionValueList(permissionValueLise2);

        return securityUser;
    }
}
